<?php
/**
 * The events class is used to trigger events
 * and bind callback functions to said events
 */
class Events {
	/**
	 * Associative array of all events and their callbacks
	 *
	 * @var array $events
	 */
	private static $events = array();

	/**
	 * Adds $callback function to $event
	 *
	 * @param string $event
	 * @param string $callback
	 */
	public static function bind ($event, $callback) {
		if (!isset(self::$events[$event])) {
			self::$events[$event] = array();
		}

		self::$events[$event][$callback] = $callback;
	}

	/**
	 * Removes $callback from $event
	 *
	 * @param string $event
	 * @param string $callback
	 */
	public static function unbind ($event, $callback) {
		if (isset(self::$events[$event][$callback])) {
			unset(self::$events[$event][$callback]);
		}
	}

	/**
	 * Triggers the selected $event - ie. runs all the callback
	 * functions (with $data passed as their first argument (unless null))
	 *
	 * @param string $event
	 * @param mixed $data
	 */
	public static function trigger ($event, $data = null) {
		if (isset(self::$events[$event])) {
			Logger::log("Triggering event \"$event\".", __METHOD__);

			$newData = $data;

			foreach (self::$events[$event] as $callback) {
				Logger::log("Running plugin \"$callback\" on event \"$event\".", __METHOD__);

				if ($data !== null) {
					$newData = $callback($newData);
				}
				else {
					$callback();
				}
			}

			Logger::log("Event \"$event\" has finished.", __METHOD__);

			return $newData;
		}

		if ($data !== null) {
			return $data;
		}
	}
}
